try {

'use strict';
var $stateProviderRef = null; //初始化路由对象（替代作用）ngAnimate
var routerApp = angular.module('jisuApp', ['ui.router', "oc.lazyLoad",'Common',"loadModule","pascalprecht.translate","720kb.tooltips","wangeditordrective"]); //我们把每个界面封装成一个模块
/*, 'loading','panel','Layer'*/
//国际化（配置） 
 routerApp.config(['$translateProvider', function ($translateProvider) {
    var lang = window.localStorage.lang;
    if(lang==null||lang==undefined||lang==""){
        lang='cn';
        window.localStorage.lang=lang;
    }
    $translateProvider.preferredLanguage(lang);
    $translateProvider.useStaticFilesLoader({
        prefix: '/framework/i18n/',
        suffix: '.json'
    });
 }]);
//国际化（模板过滤器，模板使用）
routerApp.filter("T", ['$translate', function($translate) {
    return function(key) {
        if(key){
            return $translate.instant(key);
        }
    };
}]);
//国际化（声明服务，控制器使用）
routerApp.factory('T', ['$translate', function($translate) {
    var T = {
        T:function(key) {
            if(key){              
                return $translate.instant(key);
            }
            return key;
        }
    }
    return T;
}]);

//判断有没有权限访问地址 -- 暂时没有用
routerApp.service("VerifyPermissionsService",
function() {
    this.VerifyUrl = function(obj, item) {
        if (!obj) {
            return false
        }
        var flag = false;
        for (var i = 0; i < obj.length; i++) {
            //console.log(obj[i].url);
            if (obj[i].url == item) {
                var flag = true;
                break;
            } else {
                var flag = this.VerifyUrl(obj[i].item, item);
                if (flag) {
                    break;
                }
            }
        }
        return flag;
    }
});
// 获取动态路由的数据
routerApp.factory('GetRouteList',
function($http) {
    return {
        all: function() {
            return $http({
                url: '/api/test/menu.json?v='+new Date().getTime(),
                method: 'GET'
            });
        },        
        //by函数接受一个成员名字符串和一个可选的次要比较函数做为参数
        //并返回一个可以用来包含该成员的对象数组进行排序的比较函数
        //当o[age] 和 p[age] 相等时，次要比较函数被用来决出高下
        by: function(name, minor) {
            return function(o, p) {
                var a, b;
                if (o && p && typeof o === 'object' && typeof p === 'object') {
                    a = o[name];
                    b = p[name];
                    if (a === b) {
                        return typeof minor === 'function' ? minor(o, p) : 0;
                    }
                    if (typeof a === typeof b) {
                        return a < b ? -1 : 1;
                    }
                    return typeof a < typeof b ? -1 : 1;
                } else {
                    thro("error");
                }
            }
        }
    };
});
routerApp.filter('V',["GetRouteList",function(GetRouteList){
    return function(item){        
        GetRouteList.getContext(item).success(function(data){                
            //console.log(item,SparkMD5.hash(data));   
            return item+"?version="+SparkMD5.hash(data);                             
        });     
    }
}]);
//实现无限嵌套的路由器器地址,每个界面都可以定义controller
/**
 * 由于整个应用都会和路由打交道，所以这里把$state和$stateParams这两个对象放到$rootScope上，方便其它地方引用和注入。
 * 这里的run方法只会在angular启动的时候运行一次。
 * @param  {[type]} $rootScope
 * @param  {[type]} $state
 * @param  {[type]} $stateParams
 * @return {[type]}
 */
routerApp.run(function($rootScope, $state, $stateParams, $animate, Restangular, VerifyPermissionsService, GetRouteList, sysUserInfo, Msg) {
//sysUserInfo.setuserinfo("");
    $rootScope.$state = $state;
    $rootScope.menuShow={fxs:false,gg:false,js:false,wx:false,jsb:false,wx:false};
	$rootScope.systemTitle = sysUserInfo.getuserinfo().organization_Name;

//    var title="";
//    //组织结构 ID 字符串
//    for (var i = 0; i < sysUserInfo.getuserinfo().userOrgList.length; i++) {
//        title=(title.length<=0?'':',')+sysUserInfo.getuserinfo().userOrgList[i].organization_Name;
//    }
//    if(title.length<=0){
//        title=sysUserInfo.getuserinfo().organization_Name;
//    }
//    $rootScope.systemTitle=title;

    //全局监听  当模板开始解析之前触发
    $rootScope.$on('$stateChangeStart',function(event, viewConfig){             
            //首页有图片loading，此处避过
			if(viewConfig.name!="index"){
				$rootScope.allLoadingShow = true;         
			}        
     });
     // 当模板解析完成后触发
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){                          
        $rootScope.allLoadingShow = false;
    });



    $rootScope.$stateParams = $stateParams;
    $animate.enabled(true); //启动动画    
    Restangular.addFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) {
        //这个地方需要把登录得到的token写入到请求数据的头文件中
        var usertoken  = sysUserInfo.getuserinfotoken().toString();        
        if(usertoken == undefined || usertoken == null || usertoken == ""){
              //sysUserInfo.clearuserinfo();
              localStorage.clear();
        }        
        return {              
            headers: {"X-Session-Token": usertoken,"Content-Type": "application/x-www-form-urlencoded;application/json;charset=utf-8"}  
        };
    });
    Restangular.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
        // console.log('获取数据后，对统一的错误信息进行处理 ' + data);        
        if(data.errorcode=="35"){
            Msg.error("提示","登录信息失效!");             
            sysUserInfo.clearuserinfo(); 
            data.errorcode =0;                  
        }else if(data.errorcode == "36"){
            Msg.error("提示","登录信息失效!");
            sysUserInfo.clearuserinfo();
            data.errorcode =0;                  
        }else if(data.errorcode == "38"){
        //此状态码有未知冲突，有人员新增的超出提示和？
 //           Msg.warning("提示",data.errormsg);

//            setTimeout(function(){
//                sysUserInfo.clearuserinfo();
//            },3000);
//            
//            data.errorcode =0;                  
        }
        return data;
    });
    Restangular.setErrorInterceptor(function(response, deferred, responseHandler) {
        $rootScope.errinfo="<font color=\"red\"  >服务器宕机或网络不可用！</font><a href=\"/\">重新登录</a>";
//        console.log(response.status);
        if (response.status === 200) {
            return true;
        } else {
            Msg.warning("服务器访问异常！")
            console.log('获取数据异常了！ '+response.status+","+response.data);
            // return false;
        }
    });
    $rootScope.loadshow=true;    
    var errorinfoplay = localStorage.getItem("errorinfo");
    if(errorinfoplay == null || errorinfoplay == undefined || errorinfoplay == ""){     // 从二级运营中跳转过的运营管理企业的判断
        $rootScope.errinfo="正在拼命加载中...";
    }else{
        $rootScope.errinfo = "正在为您跳转到"+errorinfoplay+"企业当中...请稍后！";
		localStorage.setItem("errorinfo","");
    }
       //通过权限，筛选菜单
            $rootScope.menufind = function (menus, perm) {
                if (menus != undefined && perm != undefined) {
                    var linshishuzu = [];
                    for (var i = 0; i < menus.length; i++) {
                        var menuobj = menus[i];
                        var rongqi = {};
                        var idx = perm.indexOf(menuobj.id);
                        //分销商
                        if(perm.indexOf('e8896a465133c9c51199048246c8cc06')!=-1){
                            $rootScope.menuShow.fxs=true;
                        //(公告-运营的id)
                        }
                         if(perm.indexOf('deb9274f9133ef419b1b5383d0bdc319')!=-1){
                            $rootScope.menuShow.gg=true;
                        //竞赛
                        }
                         if(perm.indexOf('58c40406c133edb58d769d2378f713ce')!=-1){
                            $rootScope.menuShow.js=true;
                        //问卷
                        }
                         if(perm.indexOf('99a04b351133edb58d874d9b43d0a2c2')!=-1){
                            $rootScope.menuShow.wj=true;
                        //讲师榜
                        }
                         if(perm.indexOf('97c58c9b0133ed4e1065369c9e336197')!=-1){
                            $rootScope.menuShow.jsb=true;
                        }
                        //网校
                         if(perm.indexOf('42711b04a133ee15e690878f85d6ebc0')!=-1){
                            $rootScope.menuShow.wx=true;
                        }
                        if (idx >= 0) {
                            if (menuobj.hasOwnProperty("childroute")) {
                                menuobj.childroute = angular.copy($rootScope.menufind(menuobj.childroute, perm));
                            }
                            if (menuobj.hasOwnProperty("btnlist")) {
                                menuobj.btnlist = angular.copy($rootScope.menufind(menuobj.btnlist, perm));
                            }
                            linshishuzu.push(menuobj);
                        }
                    }
                    return linshishuzu;
                }
            }

    //**********************************路由动态开始*********************
    // 1、获取用户的用户组、角色、组织机构（负责人）
    // 判断用户是否已经登录返回登录页
    if(sysUserInfo.getuserinfo()==null || sysUserInfo.getuserinfo()==""){
        window.location.href="/";
    }else{


            //2、获取全部路由的大json
            GetRouteList.all().success(function(data, header, config, status) {
                //还需要获得用户的权限，
                //参数包括用户ID，组织架构ID，角色ID，用户组ID，获得若干组权限数组，、
                //进行综合去重
                //根据权限，将菜单筛选         
//retobj.data.powerLV=="2"||       
//            if(retobj.data.powerLV=="1"){//1超级管理员、2普通管理员
            if(sysUserInfo.getuserinfo().powerLV=="1"){//1超级管理员、2普通管理员            
            //5、拿到初始化对象之后排序后遍历动态路由   生成新的路由
                data.sort(GetRouteList.by("index"));                
                $rootScope.rootscopeauthority  =data;   // 赋值给菜单中
                ergodicroute(data);//遍历路由     
                $rootScope.loadshow=false;
            }else{//3教师、99学员
//            var idstr=sysUserInfo.getuserinfo().user_ID+","+sysUserInfo.getuserinfo().orgStr+","+sysUserInfo.getuserinfo().roleStr+","+sysUserInfo.getuserinfo().groupStr;

                var idstr=sysUserInfo.getuserinfo().user_ID;      

					var copyuser=sysUserInfo.getuserinfo();
					if (copyuser.userOrgList == undefined) {
						copyuser.userOrgList = [];
					}
					if (copyuser.userRoleList == undefined) {
						copyuser.userRoleList = [];
					}
					if (copyuser.userGroupList == undefined) {
						copyuser.userGroupList = [];
					}
					sysUserInfo.setuserinfo(copyuser);
                //组织机构ID
                if(sysUserInfo.getuserinfo().userOrgList.length>0){
                    for(var i=0;i<sysUserInfo.getuserinfo().userOrgList.length;i++){
                        idstr=idstr+","+sysUserInfo.getuserinfo().userOrgList[i].organization_ID;
                    }
                }
                //权限ID
                if(sysUserInfo.getuserinfo().userRoleList.length>0){
                    for(var i=0;i<sysUserInfo.getuserinfo().userRoleList.length;i++){
                        idstr=idstr+","+sysUserInfo.getuserinfo().userRoleList[i].roles_ID;
                    }
                }
                //用户组ID
                if(sysUserInfo.getuserinfo().userGroupList.length>0){
                    for(var i=0;i<sysUserInfo.getuserinfo().userGroupList.length;i++){
                        idstr=idstr+","+sysUserInfo.getuserinfo().userGroupList[i].userGroup_ID;
                    }
                }
                //console.log(idstr);
                //4、获取用户的权限数组
        Restangular.one("/PersonnelSelector").customPOST({name: "My Message"},"GetAuthority", {bqx_xid: idstr}).then(function(retobj2) {
            if(retobj2.errorcode=="0"){
                if(retobj2.data!=null){        
                    var distributionUserInfo = sysUserInfo.getuserinfo();
                    var selList= [];// 查询list                   
                    //学员分销
                    if(distributionUserInfo.powerLV=='99'){
                        if(distributionUserInfo.hasOwnProperty('userContact')){
                            //是分销人员
                            if(distributionUserInfo.userContact.hasOwnProperty("distributionLevel")){
                                var jsonlist=angular.copy(data);
                                selList=addListByItem("e8896a465133c9c51199048246c8cc06",selList,jsonlist);
                                if(distributionUserInfo.userContact.distributionLevel == 3){
                                    selList = deleteListByItem("c2295586e133c9c4dbc18674ff927d2d",selList);
                                }
                            }
                        }else{
                            Msg.warning("你不是分销人员");
                            window.location.href="/member/index.html";
                        }
                    //管理员教师分销
                    }else{
                        selList = angular.copy(retobj2.data.bqx_quanxian.split(","));// 查询list
                        if( parseInt(distributionUserInfo.registerType) == 1 ){ // 判断是 企业
                            // 分销
                            selList = deleteListByItem("e8896a465133c9c51199048246c8cc06",selList);
                        }
                    }
                    // 如果企业不存在那么把基础模块删除掉
                    if(!distributionUserInfo.hasOwnProperty('organization_ID') ||  distributionUserInfo.organization_ID == ""){
                        selList = deleteListByItem("e34fa07de133c70710a7c269b5caad31",selList);// 培训
                        selList = deleteListByItem("6abd5fdcf133c63f10436fa3cd629803",selList);// 知识库
                        selList = deleteListByItem("5b820605e133c5dd106335caec6fdfac",selList); // 人员
                    }             

					if(distributionUserInfo.powerLV=='2'&&distributionUserInfo.hasOwnProperty("managerType")&&distributionUserInfo.managerType=='1'){
						 var jsonlist=angular.copy(data);
						selList=addListByItem("8ae44ca03133c63f104348a6070ea13f",selList,jsonlist);
					//超管
					}else if(distributionUserInfo.powerLV=='1'){
					}else{
						selList = deleteListByItem("8ae44ca03133c63f104348a6070ea13f",selList);
					}
                    // 第三方的干掉人员
                    if(distributionUserInfo.userSource == 2){
                        selList = deleteListByItem("5b820605e133c5dd106335caec6fdfac",selList);
                    }                                                                
                    data =  $rootScope.menufind(angular.copy(data),selList);//筛选出有权限的菜单
                    //5、拿到初始化对象之后排序后遍历动态路由   生成新的路由
                    data.sort(GetRouteList.by("index"));                
                    $rootScope.rootscopeauthority  =data;   // 赋值给菜单中
                    ergodicroute(data);//遍历路由
                    $rootScope.loadshow=false;
                }else{
                    $rootScope.rootscopeauthority=[];
                    $rootScope.loadshow=false;
//                    $rootScope.errinfo="请联系管理员授权！<a href=\"/\">重新登录</a>";    
                }
            }else{
            $rootScope.errinfo="罢工了...<a href=\"/\">重新登录</a>";
//                console.log(retobj2.errorcode);
            }
        });
}



            }).error(function(data, header, config, status) {
                console.log("路由获取失败!");
            });

    }
    // 删除匹配内容并返回字符串
    function deleteListByItem(item,list){
        angular.forEach(list,function(data,index){
            if(data == item)
            list.splice(index,1);
        });
        return list;
    }
	 //添加匹配内容并返回字符串
    function addListByItem(item,list,jsonList){
        //模块id
        angular.forEach(jsonList,function(data,index){
            if(data.id == item){
                list.push(data.id);
                //模块下的子集id
                if(data.hasOwnProperty('childroute')){
                    angular.forEach(data.childroute,function(data,index){
                        list.push(data.id);
                    });
                }
            }
        });
        return list;
    }
    // 真正遍历路由
    function ergodicroute(data) {
        //创建动态路由
        angular.forEach(data,
        function(value, key) {
            //判断state是否已经注册,有可能导致重复注入而报错
            //if ($state.get(value.name)) return;
            if (!value.url) return;
            // 路由对象参数
            var state = {
                "url": value.url,
                "data": {},
                "views": {},
                "resolve": {}
            };
            //有没有分块
            if (value.views) {
                var viewdata = angular.fromJson(value.views);
                angular.forEach(viewdata,
                function(value, key) {
                    state.views[value.view] = {
                        templateUrl: document.location.origin+"/system/"+value.templateURL,
                        controller: value.controller
                    };
                });
            }
            //加载文件 (数组)
            var filesdata = angular.fromJson(value.files);            
            if (filesdata!=undefined && filesdata.length > 0) {                
                state.resolve = {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            //cache: false,
                            files: filesdata
                        });
                    }]
                }
            }
            //自定义数据 -- 目前没有用到的
            state.data = {
                roles: []
            };
            //增加params配置 -- 目前没有用到的
            if (value.templateParams) {
                state.params = angular.fromJson(value.templateParams);
            }
            //注意，这个重点
            if (!$state.get(value.name)) {
                //console.log(state);    
                $stateProviderRef.state(value.name, state);
            }
            ergodicroute(value.childroute); //循环遍历子集
        });
    }
   
});
routerApp.constant('Modules_Config', [{
    name: 'gridModule',
    serie: true,
    files: [{
        type: 'css',
        path: 'http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css'
    }]
}]);
// haed
routerApp.controller("topbarController",['$scope','sysUserInfo','$rootScope','$state','$stateParams','$sce','$translate', 'Msg', 'Restangular','T', function($scope,sysUserInfo,$rootScope,$state,$stateParams,$sce,$translate, Msg, Restangular, T){
    $rootScope.parstr="index";    
    $scope.nowdate=new Date();
       // 判断客户来源用于隐藏套餐信息  
    $scope.aliFlag =  true; // 默认不是阿里的
    if(sysUserInfo.getuserinfo().hasOwnProperty("userSource") && sysUserInfo.getuserinfo().userSource == 1){
        $scope.aliFlag  =false;
    }    
    if($stateParams.routename!=undefined){ $rootScope.parstr=$stateParams.routename;}
    if($rootScope.allParstr != undefined && $rootScope.allParstr =='index.Train.course'){$rootScope.parstr = 'index.Train'} // 课程新增编辑有问题 在课程列表页初始化   
    $scope.playUrl=function(url){
		console.log(url);
        $rootScope.parstr=url;        
        $rootScope.homeparams="";
        if(url=="index.personnelmanagement"){//人员
            $state.go("index.personnelmanagement", { id: 0, routename: "index.personnelmanagement" }, { reload: true });
        }else if(url=="index.Train"){//培训
            //获取第一个菜单
            var obj;
            angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
                if(data.id =='e34fa07de133c70710a7c269b5caad31'){
                    obj = data.childroute;                          
                }
            }); 
            $rootScope.secparstr=obj[0].name;
            $state.go(obj[0].name);
        }else if(url=="index.statistics"){//资料
            $rootScope.secparstr="index.know.knowledgebase";
            $state.go("index.know.knowledgebase");
        }else if(url=="index.operate"){//运营
            $rootScope.secparstr="index.operate.home";
            $state.go("index.operate.home");

        }else if(url=="index.contentAudit"){
             //获取第一个菜单
            var obj;
            angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
                if(data.id =='6e495ac3e133ed519992249925a7b9d6'){
                    obj = data.childroute;                          
                }
            }); 
            $rootScope.secparstr=obj[0].name;
            $state.go(obj[0].name);
        }else if(url=="index.classes"){
             //获取第一个菜单
            var obj;
            angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
                if(data.id =='dcaa3df00133eede8b1664c49302693b'){
                    obj = data.childroute;                          
                }
            }); 
            $rootScope.secparstr=obj[0].name;
            $state.go(obj[0].name);
        }else{
            $rootScope.secparstr=url;
            $state.go($rootScope.secparstr);
        }
    }

    // 判断数字
    $scope.numtoInfinite = function(num,Company){
        if(num == -1 || num == 0 || num == undefined || num == null || num == "" || num =="0 KB"){
            return "未限制";
        }else{
            if(Company == undefined || Company == null || Company == ""){
                return num;
            }else{
                return num+Company;
            }                        
        }
    } 
	//是否显示
    $scope.showValidateForm=false;
	
    $scope.userinfoo = sysUserInfo.getuserinfo();
    // //退出登录
    // $scope.exituserinfo = function(){
        // sysUserInfo.clearuserinfo();
    // }
    //退出登录
    $scope.exituserinfo = function () {
        Restangular.one("/organizationInfo").customPOST({ name: "My Message" }, "findOrgInfo", { orgId: sysUserInfo.getuserinfo().organization_ID }).then(function (response) {
            var url = "//" + $rootScope.domain + "/login.html?signout=0";
            if (response.errorcode == "0") {
                if (response.data.organization_domain_name != null && response.data.organization_domain_name != "" && response.data.organization_domain_name != undefined) {
                    $scope.url = response.data.organization_domain_name;
                } else if (response.data.organization_two_domain_name != null && response.data.organization_two_domain_name != "" && response.data.organization_two_domain_name != undefined) {
                    $scope.url = response.data.organization_two_domain_name + $rootScope.shortdomain;
                } else {
                    $scope.url = $rootScope.domain;
                }
            }
            //开始跳转
            url = "http://" + $scope.url + "?signout=0";
            sysUserInfo.clearuserinfo(url);
        }, function () { sysUserInfo.clearuserinfo("//" + $rootScope.domain + "/login.html?signout=0"); });

    }
     //系统设置
    $scope.systemSet=function(){
        
        $state.go("index.manager.currency");
    }
    //系统设置
    $scope.systemSetting=function(){
        $rootScope.parstr="index.setting";
        $rootScope.secparstr="";
        try{
            var obj;
            angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
                if(data.id =='21135c76a133ee15cbc6fe7018213f3a')
                {
                    obj = data.childroute;                          
                }
            }); 
            $state.go(obj[0].name);
        }catch(e){
            Msg.warning("您没有权限！");
        }
    }
    $scope.goApi=function(){
        $rootScope.parstr="";
            $state.go("index.manager.api");
    }
    $scope.goStudent = function(){
        window.location.href="/member/index.html";
    }
    //国际化
    $scope.switching=function(lang){
        $translate.use(lang);
        window.localStorage.lang = lang;
        window.location.reload();
    };


    /***** 企业流量使用情况*****/
    $scope.operatePackageShow = false;
    $scope.operateShow = false;
    
    // 其他页面用的
    $rootScope.globalOperateObj = {};
    // 打开企业信息
    $scope.openOperate = function(){
        $scope.operateShow = true;

        $scope.liveObj = {};
        Restangular.one("/live").customPOST({name: "My Message"},"getOrgLiveState", {uid: sysUserInfo.getuserinfo().user_ID}).then(function(response) {
            if(response.errorcode=="0"){
               $scope.liveObj=JSON.parse(response.data);
               if($scope.liveObj.total==undefined){
                $scope.liveObj.total=0;
               }
            }
        });
    }
	// 获取企业套餐信息
    sysUserInfo.getOrgDetails();  	
     $scope.endShow=true;
    // 关闭企业信息
    $scope.closeOperate = function(){
        if(!$rootScope.globalOperateObj.disalbleLL){
             $scope.operateShow = false;
        }else{
            Msg.warning("您的流量已超过限制，请先扩容流量！");
        }
    }     
    //关闭过期提示
    $scope.closebottom=function(){
       $scope.endShow=false;
    }
    /***** 扩容框 *****/
    // 格式话时间
    Date.prototype.format = function(fmt) { 
         var o = { 
            "M+" : this.getMonth()+1,                 //月份 
            "d+" : this.getDate(),                    //日 
            "h+" : this.getHours(),                   //小时 
            "m+" : this.getMinutes(),                 //分 
            "s+" : this.getSeconds(),                 //秒 
            "q+" : Math.floor((this.getMonth()+3)/3), //季度 
            "S"  : this.getMilliseconds()             //毫秒 
        }; 
        if(/(y+)/.test(fmt)) {
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        }
         for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
             }
         }
        return fmt; 
    }  
    // 计算天数
    $scope.datedifference = function(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式  
        var dateSpan,
            tempDate,
            iDays;
        sDate1 = Date.parse(sDate1);
        sDate2 = Date.parse(sDate2);
        dateSpan = sDate2 - sDate1;
        dateSpan = Math.abs(dateSpan);
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
        return iDays
    };
    // 计算月数
    $scope.getMonths = function(date1 , date2){
        //用-分成数组
        date1 = date1.split("-");
        date2 = date2.split("-");
        //获取年,月数
        var year1 = parseInt(date1[0]) , 
            month1 = parseInt(date1[1]) , 
            year2 = parseInt(date2[0]) , 
            month2 = parseInt(date2[1]) , 
            //通过年,月差计算月份差
            months = (year2 - year1) * 12 + (month2-month1) + 1;
        return months;    
    }
    // 直播扩容
    $scope.liveShow=false;
    // 是否试用
    $scope.operateVip = false;
    // 套餐名称
    $scope.operateVipName = T.T("shiyongyonghu");
    // 套餐的到期时间 
    $scope.operateEndDate = new Date().format('yyyy-MM-dd');
    // 服务器的时间
    $scope.operateServerDate = new Date().format('yyyy-MM-dd');
    // token 
    $scope.expansionToken = sysUserInfo.getuserinfotoken();
    // 公共的url
    $scope.expansionUrl = commonUrl;
    // 初始化
    $scope.expansionInit = function(){
        $scope.expansionShow = false;
        // title
        $scope.expansionTitle="人数购买";
        // 单位
        $scope.expansionCompany = "人";
        // 公式 每月 每个 单位元
        $scope.expansionPublicity = 5;
        // 支付钱数
        //$scope.expansionMoney = 0;
        // 购买量
        $scope.expansionNum = 0;
        // 月数
        $scope.expansionMonth = 1;
        // 支付类型
        $scope.buyExtendType ="user";


        $scope.liveBuyState="live_scene";//直播购买状态  live_scene-场，live_month-月
        $scope.liveBuyOne=0;//直播单场价格
        $scope.liveBuyMonth=0;//直播单月价格
        // 直播购买数量
        $scope.liveBuyCount = 1;

    }
    // 获取企业的套餐情况
    $scope.operateOpenInfo = function(){
        Restangular.one("/limit").customPOST({name: "My Message"},"listOrgBuyPackageService", {userId: sysUserInfo.getuserinfo().user_ID,organizationId: sysUserInfo.getuserinfo().organization_ID}).then(function(response) {
            if(response.errorcode == "0"){
                $scope.operateServerDate = new Date(response.data.serverDate).format('yyyy-MM-dd'); // 服务器时间
                var limitList = JSON.parse(response.data.limitList);
                if(limitList != null && limitList != undefined && limitList != ""){
                    var limitState = parseInt(limitList[limitList.length - 1].limitState);
                    //读取配置，是否开启
                    $scope.operateVip = (limitState == 0)? false:true;    // 当前套餐
                    $scope.operatePackageShow = (limitState == 0)? true:false; // 显示是不是企业
                    switch (limitState) {
                        case 0: // 试用
                        $scope.operateVipName = T.T("shiyongyonghu");
                        break;
                        case 1: // 基础
                        $scope.operateVipName = T.T("jichuyonghu");
                        break;
                        case 2: // 企业
                        $scope.operateVipName = T.T("qiyeyonghu");
                        break;
                        case 3: // 集团
                        $scope.operateVipName = T.T("jituanyonghu");
                        break;
                    }
                    $scope.operateEndDate = new Date(limitList[0].limitEndDate).format('yyyy-MM-dd'); // 服务器的到期时间   
                    $scope.onMonths = $scope.getMonths($scope.operateServerDate,$scope.operateEndDate);
                    console.log($scope.onMonths);       
                }                      
            }else{
                Msg.error(T.T("cuowu"),T.T("cuowutaocantishi"));
            }
        });
    }
    $scope.operateOpenInfo();
    

    // 打开扩容
    $scope.openExpansion=function(flag){

        $scope.paydate=null;
        //请求接口  赋值
        Restangular.one("/payment").customPOST({name: "My Message"},"getPaymentDetails").then(function(response) {
            if(response.errorcode == "0"){
                console.log(response.data);
                $scope.paydate=response.data;
                // 算一下钱要交几个月的
				$scope.expansionMonth = $scope.getMonths($scope.operateServerDate,$scope.operateEndDate);  
				switch (flag) {
					case "user":    // 用户            
						$scope.expansionTitle=T.T("renyuangoumai");
						$scope.expansionCompany = T.T("People");
						//$scope.expansionPublicity = 5;         
						$scope.expansionPublicity = $scope.paydate.payment_user_amount;                     
					break;
					case "sms":     // 短信
						$scope.expansionTitle=T.T("duanxingoumai");
						$scope.expansionCompany = T.T("Strip");
						//$scope.expansionPublicity = 0.08;
						$scope.expansionPublicity = $scope.paydate.payment_sms_amount;
						// 月数
						$scope.expansionMonth = 1;
					break;
					case "storage": // 储存
						$scope.expansionTitle=T.T("cunchugoumai");
						$scope.expansionCompany = "G";
						//$scope.expansionPublicity = 0.8;
						$scope.expansionPublicity = $scope.paydate.payment_storage_amount;
					break;
					case "email":   // 邮件
						$scope.expansionTitle=T.T("youjiangoumai");
						$scope.expansionCompany = T.T("feng");
						//$scope.expansionPublicity = 0.01;
						$scope.expansionPublicity=$scope.paydate.payment_email_amount;
						// 月数
						$scope.expansionMonth = 1;
					break;
					case "flow":    // 流量
						$scope.expansionTitle=T.T("liulianggoumai");
						$scope.expansionCompany = "G";
						//$scope.expansionPublicity = 0.8;
						$scope.expansionPublicity = $scope.paydate.payment_flow_amount;
						// 月数
						$scope.expansionMonth = 1;
					break;     
                    case "live":    // 直播
                        //$scope.expansionPublicity = 0.8;
                        $scope.expansionPublicity = $scope.paydate.payment_flow_amount;
                        $scope.liveBuyOne=$scope.paydate.payment_live_scene_amount;//单场价格
                        $scope.liveBuyMonth=$scope.paydate.payment_live_month_amount;//单月价格
                        // 购买数量
                        $scope.liveBuyCount = 1;

                        $scope.liveShow=true;
                    break;      
				}
				$scope.buyExtendType =flag;

                if(flag!="live"){
                    $scope.expansionShow = true;
                }
				
            }else{
                 console.log("bug来串门!");
            }
        });

        
    }
    $scope.expansionInit();
    // 关闭扩容
    $scope.closeExpansion =function(){
        $scope.expansionInit();        
    }   
    $scope.closeLive=function(){
        $scope.liveShow=false;
    }
    $scope.payContinue = false;
    // 去支付
    $scope.pay = function(){
        $scope.expansionInit();        
        $scope.operateShow = false;
         $scope.liveShow=false;
        $scope.payContinue = true;        
    }
    // 关闭支付
    $scope.closePay = function(flag){
        if(flag){
            window.location.reload();
        }else{
             if($rootScope.globalOperateObj.disalbleLL){
                //打开弹框
                $scope.openOperate();
             }
        }
        $scope.payContinue = false;
    }
    // 输出进度条
    $scope.getProgressHtml = function(num,max){
        var jindu = ((parseFloat(num)/parseFloat(max))*100 >= 100 ? 100 :(parseFloat(num)/parseFloat(max))*100) + '%';
        return jindu;// $sce.trustAsHtml('<i style="width:'+jindu+'"></i>');
    }
	 //展开流量扩容
    $scope.$watch('globalOperateObj.disalbleLL', function (newValue, oldValue, scope) {
        if ($rootScope.globalOperateObj.disalbleLL) {
            //打开弹框
            $scope.openOperate();
        }
    },true);
}]);
/********************************************************企业客服******************************************************************/
//企业联系人
routerApp.controller("orgCustomerController",['$scope','sysUserInfo','$state','$location','$rootScope','Restangular','MsgCon','Msg', function($scope,sysUserInfo,$state,$location,$rootScope,Restangular,MsgCon,Msg){
    /**********************判断是不是第一次使用向导*********************/
    $scope.guideShow= sysUserInfo.getLS("guideShow_"+sysUserInfo.getuserinfo().user_ID);
    if(!$scope.guideShow){
        $scope.guideShow = true;
        sysUserInfo.setLS("guideShow_"+sysUserInfo.getuserinfo().user_ID,true);
    }else{$scope.guideShow = false;}   
   $scope.orgCustomerList={};
   $scope.codeState=0;
   $scope.closeKefu=false;
       /*****************获取企业联系人******************************/
  $scope.getorgCusList=function(){
     Restangular.one("/PersonnelManagement").customPOST({name: "My Message"},"CustomerList", {orgid: sysUserInfo.getuserinfo().organization_ID}).then(function(response) {
            if(response.errorcode=="0"){
               $scope.orgCustomerList=response.data;
            }else if(response.errorcode=="50"){
                $scope.codeState=50;
            }else{
                console.log("获取企业联系人失败");
            }
            $scope.closeKefu=true;
        });
   }
   $scope.getorgCusList();
   //是否关闭客服
   $scope.closeKefuWindow=function(){
        $scope.closeKefu=!$scope.closeKefu;
   }
   $scope.sysInfo=sysUserInfo.getuserinfo();
   
   var guid = new GUID();
   //新增课件    
   $scope.newckt=function(){        
        var ckturl = "/wk/index.html?callback="+commonUrl+"/Kapi/AddEditURLCollection"
       // var ckturl = "http://ke.edu-paas.com/system/index.html?callback="+commonUrl+"/Kapi/AddEditURLCollection"
        var user = sysUserInfo.getuserinfo();
        var orgid =user.organization_ID;
        var canshu = "&type=0&key="+guid.newGUID();
        canshu +="&fid=0";//父级ID
        canshu +="&fpath=/";//显示路径
        canshu +="&upOrgId="+orgid+"&uid="+orgid+"";//企业ID
        canshu +="&upUserId="+user.user_ID;//用户ID
        canshu +="&upUserName="+encodeURI(encodeURI(user.user_Name));//用户名（编码）        
        window.open(ckturl + canshu);             
   }    
   // 上传文件工具  
   $scope.upFileTool = function(){
        window.open("http://www.jisupeixun.com/home/helpinfo?key=5d1492e6-60cb");
   }
   //快捷方式
   $scope.playUrl=function(url){
        try{
            $rootScope.parstr="kjfs";
            $rootScope.homeparams=url;
            $state.go(url);
        }catch(e){
            Msg.warning("你没有权限！");
        }
   }
    // 网校
   $scope.wxUrl =function(){
        $rootScope.parstr="kjfs";
        $rootScope.secparstr="index.setting.onlineschool";
        $state.go($rootScope.secparstr);
   }
   $scope.showMenul=function(id){
        console.log($rootScope.rootscopeauthority);
        return;
        if($rootScope.rootscopeauthority){
            return true;
        }else{
            return false;
        }
   }
   // 笔记本配置
   $scope.configbtnjishiben= ['undo', 'redo', '|','bold', 'underline', 'italic', 'strikethrough','eraser','forecolor', '|',  'quote','fontsize', 'head','unorderlist','orderlist', 'alignleft', 'aligncenter','alignright', '|', 'img','insertcode', ];   
   $scope.closenotepad = function () {
        $scope.uuid="";
        $scope.shownotepad = false;
        $scope.isbtnload = false;
        $scope.kbinfo.fileTxt="";
    }
   $scope.shownotepad = false;
   $scope.kbinfo = { "upUserId": sysUserInfo.getuserinfo().user_ID, "upOrgId": sysUserInfo.getuserinfo().organization_ID, "upUserName": sysUserInfo.getuserinfo().username, "fileName": "", "fpath": "/", "fid": "0", "upId": $scope.uuid, "fileTxt": "", "strName": "" };                    
   // 打开记事本
   $scope.addnotepad = function () {        
            $scope.uuid=guid.newGUID();            
            $scope.kbinfo.fileTxt = "";
            $scope.shownotepad = true;
            $scope.kbinfo = { "upUserId": sysUserInfo.getuserinfo().user_ID, "upOrgId": sysUserInfo.getuserinfo().organization_ID, "upUserName": sysUserInfo.getuserinfo().username, "fileName": "", "fpath": "/", "fid": "0", "upId": $scope.uuid, "fileTxt": "", "strName": "" };                    
    }
    // 保存记事本
    $scope.savenotepad = function () {
        if($scope.kbinfo.fileTxt == ""||$scope.kbinfo.fileTxt ==null) {
            Msg.info("添加记事本内容不能为空！");
            return;
        }
         $scope.kbinfo.strName = delHtmlTag($scope.kbinfo.fileTxt).substring(0, 12);
         if($scope.kbinfo.strName==""){
                $scope.kbinfo.strName = "图片文件";
         }   
        $scope.newSaveObj=angular.copy($scope.kbinfo);
        $scope.newSaveObj.fileTxt = encodeURIComponent($scope.newSaveObj.fileTxt);
        $scope.isbtnload = true;
        Restangular.one("/Kapi").customPOST({ name: "My Message" }, "AddNotepad", $scope.newSaveObj).then(function (kbdata) {            
            if (kbdata.errorcode == 0) {
                $scope.shownotepad = false;                
                $scope.isbtnload = false;                                                     
                Msg.success("保存成功！");                 
            } else if (kbdata.errorcode == 29) {
                Msg.info("记事本名称已经存在");
            } else if (kbdata.errorcode == 39) {
                Msg.warning("警告", "存储空间超过最大限制");
            } else {
                Msg.error("操作失败！");
            }
        }, function callback() {
            Msg.error("请求数据异常！");
        });
    }
    function delHtmlTag(str) {
        if (str != undefined && str != null && str != "") {
            return str.replace(/<[^>]+>/g, ""); //去掉所有的html标记
        } else {
            return "";
        }
    }
}]);
/*************************************************************************************************************************/
//培训
routerApp.controller("peixunController",['$scope','sysUserInfo','$state','$rootScope',function($scope,sysUserInfo,$state,$rootScope){
//    $scope.secparstr="";
    $scope.playUrl=function(url){
		console.log(url);
        $rootScope.secparstr=url;
        if(url=="index.Train.lukecheng"){
            $state.go($rootScope.secparstr,{courid:"e579b27e-e12d-458c-98a2-40c80412e497"});
        }else{
            $state.go($rootScope.secparstr,{examid:""});
        }
    }
      $scope.childobj = function(){        
        var obj;
        angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
            if(data.id =='e34fa07de133c70710a7c269b5caad31')
            {
                obj = data;                          
            }
        });                
        return obj;
    }
    $scope.personnelauthority = $scope.childobj().childroute; 

    var navigalist = $scope.personnelauthority;
    var paramflag=false;
    var paramname="";
    for(var i=0;i<navigalist.length;i++){
        if($rootScope.secparstr!="" && navigalist[i].name.indexOf($rootScope.secparstr)>=0){
            $scope.playUrl(navigalist[i].name);
            paramflag=true;
        }
        if(navigalist[i].index==0){
                  paramname=navigalist[i].name;      
        }
    }
    if (!paramflag) {
        if (paramname != "") {
            $scope.playUrl(paramname);
        } else if ($rootScope.homeparams!=undefined&&$rootScope.homeparams != "") {
            $scope.playUrl($rootScope.homeparams);
        } else {
           $scope.playUrl(navigalist[0].name);
        }
    }
    
}]);

//考试
routerApp.controller("examController",['$scope','sysUserInfo','$state','$rootScope',function($scope,sysUserInfo,$state,$rootScope){
//    $scope.parstr="";        
    $scope.playUrl=function(url){
        $rootScope.secparstr=url;
        $state.go($rootScope.secparstr);
    }

      $scope.childobj = function(){        
        var obj;
        angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
            if(data.id =="e34fa07de133c70710a7c269b5caad31")
            {
                obj = data;                          
            }
        });                
        return obj;
    }
    $scope.personnelauthority = $scope.childobj().childroute;   

    var navigalist = $scope.personnelauthority;
    var paramflag=false;
    var paramname="";
    for(var i=0;i<navigalist.length;i++){
        if(navigalist[i].name.indexOf($rootScope.secparstr)>=0){
            $scope.playUrl(navigalist[i].name);
            paramflag=true;
        }
        if(navigalist[i].index==0){
                  paramname=navigalist[i].name;      
        }
    }
    if (!paramflag) {
        if (paramname != "") {
            $scope.playUrl(paramname);
        } else if ($rootScope.homeparams != ""&&$rootScope.homeparams!=undefined) {
            $scope.playUrl($rootScope.homeparams);
        } else {
           $scope.playUrl(navigalist[0].name);
        }
    }
}]);

//统计
routerApp.controller("tongjiController",['$scope','sysUserInfo','$state','$rootScope',function($scope,sysUserInfo,$state,$rootScope){
//    $scope.parstr="";        
    $scope.playUrl=function(url){
        $rootScope.secparstr=url;
        $state.go($rootScope.secparstr);
    }

}]);

//运营
routerApp.controller("operateController",['$scope','sysUserInfo','$state','$rootScope',function($scope,sysUserInfo,$state,$rootScope){
    $scope.powerLv = sysUserInfo.getuserinfo().powerLV;
//    $scope.parstr="";        
    $scope.playUrl=function(url){
        $rootScope.secparstr=url;
        $state.go($rootScope.secparstr);
    }    
    $scope.childobj = function(){         // 获取子导航
        var obj;
        angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
            if(data.id =='8ae44ca03133c63f104348a6070ea13f')
            {                
                obj = data;                          
            }
        });                
        return obj;
    }    
    $scope.personnelauthority = $scope.childobj().childroute;       
    $scope.playUrl($rootScope.secparstr);

}]);
//班级
routerApp.controller("classesHomeController",['$scope','sysUserInfo','$state','$rootScope',function($scope,sysUserInfo,$state,$rootScope){
    $scope.playUrl=function(url){
		console.log(url);
        $rootScope.secparstr=url;
        $state.go(url);
    }
      $scope.childobj = function(){        
        var obj;
        angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
            if(data.id =='dcaa3df00133eede8b1664c49302693b')
            {
                obj = data;                          
            }
        });                
        return obj;
    }
    $scope.personnelauthority = $scope.childobj().childroute; 

    var navigalist = $scope.personnelauthority;
    var paramflag=false;
    var paramname="";
    for(var i=0;i<navigalist.length;i++){
        if($rootScope.secparstr!="" && navigalist[i].name.indexOf($rootScope.secparstr)>=0){
            $scope.playUrl(navigalist[i].name);
            paramflag=true;
        }
        if(navigalist[i].index==0){
                  paramname=navigalist[i].name;      
        }
    }

    if (paramname != "") {
        $scope.playUrl(paramname);
    } else if ($rootScope.homeparams!=undefined&&$rootScope.homeparams != "") {
        $scope.playUrl($rootScope.homeparams);
    } else {
        $scope.playUrl(navigalist[0].name);
    }

    
}]);

// 向config 中注入的服务， 可以赋值之后再controller 中获取数据
routerApp.provider("testser",
function() {   
    var name = "";
    this.settest = function(a) {
        name = a;
        return;
    }
    this.$get = function($http, $q) {
        return {
            getData: function() {
                var d = $q.defer();
                $http.get("url") //读取数据的函数。
                .success(function(response) {
                    d.resolve(response);
                }).error(function() {
                    d.reject("error");
                });
                return d.promise;
            }            
        }
    }
});
/**
 * 配置路由。
 * 注意这里采用的是ui-router这个路由，而不是ng原生的路由。
 * ng原生的路由不能支持嵌套视图，所以这里必须使用ui-router。
 * main@index的意思是main是view标签的名字
 * @param  {[type]} $stateProvider
 * @param  {[type]} $urlRouterProvider
 * @return {[type]} toastrConfig 配置消息弹出样式
 * @return {[type]} RestangularProvider 数据请求
 */
routerApp.config(['$stateProvider', '$urlRouterProvider', '$oclazyloadProvider', 'toastrConfig',  'Modules_Config',
function($stateProvider, $urlRouterProvider, $oclazyloadProvider, toastrConfig,  Modules_Config) {
    //全局设置AJAX数据请求地址       
    //RestangularProvider.setRequestSuffix('.json'); //这个后缀名在正式项目中删除掉    
    $stateProviderRef = $stateProvider; //将定义路由的对象赋值给定义好的变量方便抛出使用原因是config 中不能用区域变量
    //配置异步加载器
    $oclazyloadProvider.config({
        debug: false,
        events: false,
        modules: Modules_Config
    });

    //配置路由器
    $urlRouterProvider.otherwise('/index');
    $stateProvider.state('index', {
        url: '/index',
        data: {},
        views: {
            '': {
                templateUrl: 'views/index.html'
            },
            'topbar@index': {
                templateUrl: 'views/topbar.html',
                controller: function($scope, toastr) {
                    if(false)
                    toastr.success('这是一个alert的提示窗口', '系统提示');

                }
            },
            'main@index': {
                templateUrl: 'views/home.html'
            }
        },
        resolve: {
 modules: ['$oclazyload',
            function($oclazyload) {
                return $oclazyload.load([{
                    name: "indexHome",
                    files: [commonFileUrl+"/resources/pdf2/pdf.js","/system/controller/home.js"]
                }]);
            }]
        }
    })

    // *******************************培训--培训课程*************************
    .state('index.Train.traincurriculum', {
        url: '/traincurriculum',
        templateUrl: 'views/Train/traincurriculum.html'
    })
    //    课程制作
    .state('index.Train.course.lukecheng', {
        url: '/lukecheng/:courid/:studycount',
        views: {
            'main@index.Train.course': {
                // controller: 'democontroller', 
                templateUrl: document.location.origin+"/system/"+'views/train/traincurriculum/lukecheng.html'
            }
        },
        resolve: {
            modules: ['$oclazyload',
            function($oclazyload) {
                return $oclazyload.load({
                    module: 'lukecheng',
                    files: ['/system/service/statisticservice.js','/system/service/trainpathservice.js', '/system/directive/wangeditor.js','/system/controller/train/traincurriculum/lukecheng.js']
                });
            }]
        }
    })
    

    .state('index.personnelmanagement.newlyadded', {
        url: '/newlyadded',
        //注意这里在路由中传参数的方式           
        views: {
            'PmMain@index.personnelmanagement': {
                // controller: 'democontroller',
                templateUrl: 'views/personnel/newlyadded.html'
            }
        }
    })

    .state('index.Train.customReport', {
        url: '/customReport',
        params:{ userObj: ""},
        views: {
            'main@index.Train': {
                templateUrl: 'views/statistics/reportform.html'
            }
        },
        resolve: {
            modules: ['$oclazyload',
            function($oclazyload) {
                return $oclazyload.load({
                    serie: true,
                    cache: false,
                    files: ["controller/statistics/reportform.js"]

                });
            }]
        }
    })


		


}]);



} catch (e) {
console.log(e);
}